<?php

namespace Classes;

if (!defined('CACHE_PATH'))
	define('CACHE_PATH', __DIR__ . DIRECTORY_SEPARATOR . 'Cache' . DIRECTORY_SEPARATOR, false);

class Cache {
	/**
	 * 缓存数据到文件
	 *
	 * @param  string  $key     缓存key, \w+
	 * @param  mixed   $data    缓存数据
	 * @param  int     $expire  缓存过期时间(秒)，<=0表示不过期
	 *
	 * @return bool
	 */
	public static function set ($key, $data, $expire = 0) {
		if ($data === null) return false;

		if (!is_dir(CACHE_PATH) && !mkdir(CACHE_PATH, 0777, true))
			return false;

		$key     = self::filter_key($key);
		$path    = CACHE_PATH . $key . '.cache.php';
		$time    = time();
		$content = "<?php" . PHP_EOL;
		$content .= '//缓存创建时间：' . date('Y-m-d H:i:s', $time) . PHP_EOL . PHP_EOL;
		if ($expire > 0) {
			$content .= '//缓存过期时间' . PHP_EOL;
			$content .= '$_expire_' . $key . " = '" . date('Y-m-d H:i:s', $time + $expire) . "';" . PHP_EOL . PHP_EOL;
		}
		$content .= 'return ' . var_export($data, true) . ";";

		return false !== file_put_contents($path, $content, LOCK_EX);
	}

	/**
	 * 获取缓存数据
	 *
	 * @param  string|array  $key  缓存key, \w+
	 *
	 * @return mixed|null 成功：缓存文件内的数据，失败：null
	 */
	public static function get ($key) {
		$key             = self::filter_key($key);
		$cache_file_path = CACHE_PATH . $key . '.cache.php';
		if (is_file($cache_file_path)) {
			$result     = include $cache_file_path;
			$expire_var = '_expire_' . preg_replace('/\W/', '', $key);
			if (strtotime($$expire_var) > time()) return $result;
			self::delete($key);
		}

		return null;
	}

	/**
	 * 删除缓存
	 *
	 * @param  string  ...$key  缓存key, \w+
	 *
	 * @return void
	 */
	public static function delete (...$key) {
		foreach ($key as $name) {
			$name            = self::filter_key($name);
			$cache_file_path = CACHE_PATH . $name . '.cache.php';
			if (is_file($cache_file_path)) @unlink($cache_file_path);
		}
	}

	private static function filter_key ($key) {
		return preg_replace('/(\W|^\d)/', '_', $key);
	}
}

/*var_dump(Cache::set('cs', ['v' => '测试'], 10));
var_dump(Cache::get('cs'));*/